package com.nanbei.queue;

import java.util.Deque;
import java.util.Iterator;

/**
 * @ClassDescription: 基于数组实现的双端队列
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/28 15:11
 */
public class ArrayDeque<E> implements DequeInterface<E>,Iterable<E> {

    E[] array;
    int head ,tail;
    int size;

    @SuppressWarnings("all")
    public ArrayDeque(int size) {
        this.array = (E[]) new Object[size+1];
        this.head = 0;
        this.tail = 0;
        this.size = size+1;
    }

    @Override
    public boolean offerFirst(E value) {
        if (isFull()){
            return false;
        }
        head = dec(head,size);
        array[head] = value;
        return true;
    }

    @Override
    public boolean offerLast(E value) {
        if (isFull()){
            return false;
        }
        array[tail] = value;
        tail = inc(tail,size);
        return true;
    }

    @Override
    public E pollFirst() {
        if (isEmpty()){
            return null;
        }
        E e = array[head];
        array[head] = null;
        head = inc(head, size);
        return e;
    }

    @Override
    public E pollLast() {
        if (isEmpty()){
            return null;
        }
        tail = dec(tail,size);
        E e = array[tail];
        array[tail] = null;
        return e;
    }

    @Override
    public E peekFirst() {
        if (isEmpty()){
            return null;
        }
        return array[head];
    }

    @Override
    public E peekLast() {
        if (isEmpty()){
            return null;
        }
        return array[dec(tail,size)];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return inc(tail,array.length) == head;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
             int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E e = array[p];
                p = inc(p,size);
                return e;
            }
        };
    }

    static int inc(int i, int length) {
        if (i + 1 >= length) {
            return 0;
        }
        return i + 1;
    }

    static int dec(int i, int length) {
        if (i - 1 < 0) {
            return length - 1;
        }
        return i - 1;
    }
}
